import { SelectionRange } from "@/types/common";
import { useCursorManager } from "./useCursorManager";
import { createApp, h, Ref } from "vue";
import { MessageType, TacticMessageType } from "@/types/chat";

interface IEditor {
  selection: Selection;
  range: Range;
}

export function useCommon() {
  let { GetLastSelection } = useCursorManager();

  // 获取编辑器
  function GetEditor(): IEditor | null {
    if (window.getSelection) {
      const selection = window.getSelection();
      if (!selection || selection.rangeCount === 0) {
        const inputElement = document.getElementById("message-input");
        if (inputElement) {
          console.log(inputElement, "1123");
          inputElement.focus();
          const range = document.createRange();
          // 将光标移动到输入框的最后
          range.selectNodeContents(inputElement);
          range.collapse(false); // 折叠到末尾
          selection?.removeAllRanges();
          selection?.addRange(range);
        }
      }
      // 重新检查
      if (selection && selection.rangeCount) {
        const range = selection.getRangeAt(0);
        return { range, selection };
      }
    }
    return null;
  }

  // 插入文本
  function InsertTextNode(InputElement: HTMLElement, text: string) {
    let lastEditRange: SelectionRange | null = GetEditor();
    if (!lastEditRange) {
      const selection = window.getSelection();
      if (selection && selection.rangeCount > 0) {
        lastEditRange = {
          range: selection.getRangeAt(0),
          selection,
        };
      } else {
        const range = document.createRange();
        range.selectNodeContents(InputElement);
        range.collapse(false);
        lastEditRange = {
          range,
          selection: window.getSelection()!,
        };
      }
    }
    const selection = window.getSelection();
    if (selection) {
      selection.removeAllRanges();
      selection.addRange(lastEditRange.range);
    }
    lastEditRange.range.deleteContents();
    lastEditRange.range.insertNode(document.createTextNode(text));
    lastEditRange.range.collapse(false);
    lastEditRange.selection.collapseToEnd();
  }

  // 插入图片
  function InsertImgNode(file: any, inputElement: HTMLElement) {
    if (typeof file == "string") {
      console.log("执行了");

      HandelRange(CreateImage(file), inputElement);
      return;
    }
    console.log("不是string");

    const reader = new FileReader();
    reader.onload = (e: ProgressEvent<FileReader>) => {
      const imageSrc = e.target?.result;
      if (!imageSrc) return;
      HandelRange(CreateImage(imageSrc as string), inputElement);
    };
    reader.readAsDataURL(file);
  }

  // 创建图片
  function CreateImage(imageSrc: string): HTMLElement {
    const img = document.createElement("img");
    img.src = imageSrc as string;
    Object.assign(img.style, {
      maxHeight: "68px",
      maxWidth: "100px",
      marginRight: "6px",
      display: "inline-block",
    });
    return img;
  }

  //处理插入图片光标
  function HandelRange(img: HTMLElement, inputElement: HTMLElement) {
    // 获取最后一次光标位置
    const lastEditRange = GetLastSelection();
    inputElement.focus();
    let range: Range;
    if (!lastEditRange) {
      range = document.createRange();
      range.selectNodeContents(inputElement);
      range.collapse(false);
    } else {
      range = lastEditRange.range;
    }
    const selection = window.getSelection();
    if (selection) {
      range.deleteContents();
      const span = document.createElement("span");
      span.textContent = "\u200B";
      span.style.display = "none";
      range.insertNode(span);
      range.setStartAfter(span);
      range.insertNode(img);
      range.setStartAfter(img);
      range.setEndAfter(img);
      selection.removeAllRanges();
      selection.addRange(range);
    }
    TriggerInputEvent(inputElement);
  }

  // 插入@xxx
  function InsertAitNode(_type: string, text: string, _target: HTMLElement) {
    const { range, selection } = GetEditor()!;
    range.deleteContents();
    const spanNode = document.createElement("span");
    spanNode.id = "aitSpan";
    spanNode.contentEditable = "false";
    spanNode.classList.add("text-blue-500");
    spanNode.classList.add("select-none");
    spanNode.classList.add("cursor-default");
    spanNode.style.userSelect = "text";
    spanNode.appendChild(document.createTextNode(`@${text}`));
    range?.insertNode(spanNode);
    range?.collapse(false);
    const spaceNode = document.createTextNode("\u00A0");
    range?.insertNode(spaceNode);
    selection.collapseToEnd();
  }

  // 插入quotation引用
  function InsertReferMenNode(messageInputEle: HTMLElement, component: any, params: Record<any, any>) {
    if (!messageInputEle) return;

    const realDom = RenderRealDom(component, params);
    const editor = GetEditor();
    if (!realDom || !editor) return;

    const { range, selection } = editor;
    const hasChildren = messageInputEle.hasChildNodes();
    const existing = messageInputEle.querySelector("#quotation");

    messageInputEle.focus();

    if (existing) {
      existing.replaceWith(realDom);
    } else {
      if (hasChildren) selection.setPosition(selection.anchorNode, 0);

      const r = selection.getRangeAt(0);
      r.insertNode(realDom);
      r.collapse(false);

      if (hasChildren) {
        selection.removeAllRanges();
        selection.addRange(range);
      } else {
        const spaceNode = Object.assign(document.createElement("span"), {
          textContent: "\u00A0",
          contentEditable: "false",
          style: { userSelect: "none" },
        });
        r.insertNode(document.createTextNode(""));
        r.insertNode(spaceNode);
        r.collapse(false);
      }
    }
  }

  // 触发input事件
  function TriggerInputEvent(element: HTMLElement) {
    if (element) {
      const event = new Event("input", {
        bubbles: true,
        cancelable: true,
      });
      element.dispatchEvent(event);
    }
  }

  // 移除tag
  function RemoveTag(fragment: string) {
    const doc = new DOMParser().parseFromString(fragment, "text/html");
    let result = "";
    doc.body.childNodes.forEach((node) => {
      if (node.nodeType === Node.TEXT_NODE && node.textContent && node.textContent.trim() !== "") {
        result += node.textContent.trim() + " ";
      }
    });
    return result.trim();
  }

  //获取消息类型
  function GetMessageContentType(inputElement: Ref): TacticMessageType {
    const elements = inputElement.value.childNodes;
    let hasText = false;
    let hasImage = false;

    for (const element of elements) {
      if (element.nodeType === Node.TEXT_NODE && element.nodeValue?.trim()) {
        hasText = true;
      } else if (element.tagName === "IMG") {
        hasImage = true;
      }
      if (hasText && hasImage) {
        return MessageType.mixTxtImg; // 优先返回混合类型
      }
    }

    if (hasImage) return MessageType.image;
    if (hasText) return MessageType.text;
    return MessageType.text;
  }

  // 根据虚拟dom生成真实dom
  function RenderRealDom(vNode: any, params: Record<any, any>): Element | null {
    if (!vNode) return null;
    const v = h(vNode, params);
    const div = document.createElement("div");
    const app = createApp(v);
    app.mount(div);
    return div.firstElementChild!;
  }

  return {
    GetEditor,
    InsertTextNode,
    InsertAitNode,
    InsertReferMenNode,
    TriggerInputEvent,
    InsertImgNode,
    RemoveTag,
    GetMessageContentType,
  };
}
